import json
from datetime import datetime
import backtrader as bt
import akshare as ak
import pandas as pd
import time

# 要计算的列表
lst = [
    '600519',
    '000651',
    '600612',
    '600602',
    '600660',
    '600887',
    '000568',
    '300033',
    '600621',
    '000858'
       ]

def do():
    start = '20201201'
    end = '20250107'
    stock_info_a_code_name_df = ak.stock_info_a_code_name()
    j = json.loads('{}')
    j_lst = []
    for i in lst:
        one = {}
        name = stock_info_a_code_name_df[stock_info_a_code_name_df['code'] == i].iloc[0].tolist()[1]
        one['名称'] = name
        stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol=i, period="daily", start_date=start, end_date=end, adjust="")
        # 最后180项
        stock_zh_a_hist_df = stock_zh_a_hist_df.tail(180)
        one['代码'] = i
        one['平均成交量'] = stock_zh_a_hist_df['成交量'].mean()
        one['平均成交额'] = stock_zh_a_hist_df['成交额'].mean()
        one['平均最高价'] = stock_zh_a_hist_df['最高'].mean()
        one['平均最低价'] = stock_zh_a_hist_df['最低'].mean()
        one['平均开盘价'] = stock_zh_a_hist_df['开盘'].mean()
        one['平均收盘价'] = stock_zh_a_hist_df['收盘'].mean()

        stock_a_indicator_lg_df = ak.stock_a_indicator_lg(symbol=i)
        stock_a_indicator_lg_df = stock_a_indicator_lg_df.tail(180)
        one['平均市盈率'] = stock_a_indicator_lg_df['pe'].mean()
        one['平均市盈率TTM'] = stock_a_indicator_lg_df['pe_ttm'].mean()
        one['平均市净率'] = stock_a_indicator_lg_df['pb'].mean()
        one['平均市销率'] = stock_a_indicator_lg_df['ps'].mean()
        one['平均市销率TTM'] = stock_a_indicator_lg_df['ps_ttm'].mean()
        one['平均总市值'] = stock_a_indicator_lg_df['total_mv'].mean()

        j_lst.append(one)
        print(f'{i} is ok')
        time.sleep(2)

    j['data'] = j_lst
    j = json.dumps(j,ensure_ascii=False)
    with open('推荐股近180天平均数据.json','w',encoding='utf-8') as f:
        f.write(j)

if __name__ == '__main__':
    do()


